package com.hh.TreeQuestions;

import java.util.LinkedList;
import java.util.Queue;

/**
 * 填充每个节点的下一个右侧节点指针
 * 很久没做 有点忘了 原理不难
 * middle
 * 注意： 这里要用到get()  所以不能用Queue要用LinkedList
 */

public class No116 {
    // Definition for a Node.
    class Node {
        public int val;
        public Node left;
        public Node right;
        public Node next;

        public Node() {}

        public Node(int _val) {
            val = _val;
        }

        public Node(int _val, Node _left, Node _right, Node _next) {
            val = _val;
            left = _left;
            right = _right;
            next = _next;
        }
    }

    public Node connect(Node root) {
        if (root == null) {
            return root;
        }
        LinkedList<Node> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            //将队列中的元素串联起来
            Node tempNode = queue.get(0);
            for (int i = 1; i < size; i++) {
                tempNode.next = queue.get(i);
                tempNode = queue.get(i);
            }
            //遍历队列中的每个元素，将每个元素的左右节点也放入队列中
            for (int i = 0; i < size; i++) {
                tempNode = queue.poll(); //这时候才从队列中取出节点
                if (tempNode.left != null) {
                    queue.offer(tempNode.left);
                }
                if (tempNode.right != null) {
                    queue.offer(tempNode.right);
                }
            }
        }
        return root;
    }
}
